package br.com.escolaespacocrianca.fineec.business;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;

import org.hibernate.Session;

import br.com.caelum.vraptor.ioc.Component;
import br.com.escolaespacocrianca.fineec.model.Enrollment;
import br.com.escolaespacocrianca.fineec.model.ExtraService;
import br.com.escolaespacocrianca.fineec.model.Month;
import br.com.escolaespacocrianca.fineec.model.Plot;

@Component
public class ExtraServiceBusiness extends EntityBusiness<ExtraService> {
	
	public ExtraServiceBusiness(Session session) {
		super(session,new ExtraService());
	}
	
	@Override
	protected void updateEntityInformations(ExtraService t, ExtraService tToUpdate) {
		
		
		
		
		tToUpdate.setPrice(t.getPrice());
		tToUpdate.setType(t.getType());
		tToUpdate.setPlots(t.getPlots());
		tToUpdate.setNumberOfPlots(t.getNumberOfPlots());
		
		//TODO Colocar Status em Extra Service como em Enrollment
		if( tToUpdate.getId() == null){
			
			List<Plot> plots = new ArrayList<Plot>();
			
			for (int i = 0; i < t.getNumberOfPlots();i++){
				Plot plot = new Plot();
				
				plot.setPrice(t.getPrice() / t.getNumberOfPlots());
				//plot.setDayOfPayment(enrollmentFull.getDayOfPayment());
				
				GregorianCalendar calendar = new GregorianCalendar();
				int month = calendar.get(GregorianCalendar.MONTH);
				plot.setMonth(Month.values()[month + i]);
				
				plots.add(plot);
			}
			
			tToUpdate.setPlots(plots);
		}
		
	}

	@Override
	protected void beforeDelete(ExtraService t) {
		for(Plot plot: t.getPlots()){
			plot.delete();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<ExtraService> searchByEnrollment(Enrollment enrollment) {

		List<ExtraService> extraServices = (List<ExtraService>) session.createQuery(
				"from ExtraService as e where e.enrollment.id = :pEnrollmentId and e.deleted = false").setInteger("pEnrollmentId", enrollment.getId()).list();

		return extraServices;
	}
	
}
